package com.df.excel_export.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.df.excel_export.common.*;
import com.df.excel_export.project_config.ProjectConfig;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ExcelEnumReadListener implements ReadListener<Map<Integer, String>> {

    private boolean isParseEnum = false;
    List<ExcelEnum> excelEnums = new ArrayList<>();
    ExcelEnum nowEnum = null;
    ProjectConfig cfg;
    public ExcelEnumReadListener( ProjectConfig cfg) {
        this.cfg = cfg;
    }


    @Override
    public void invoke(Map<Integer, String> rowData, AnalysisContext analysisContext) {
        if(!ExportTask.canContinue()){
            return;
        }
        String cellOne = rowData.get(0);
        if(!isParseEnum){
            if(cellOne==null || cellOne.isEmpty()){
                return;
            }
            if(cellOne.startsWith("@")){
                isParseEnum = true;
                nowEnum = new ExcelEnum();
                if(rowData.size()>1){
                    nowEnum.setDesc(rowData.get(1));
                }
                nowEnum.setName(cellOne.replace("@","").trim());
                return;
            }
            return;
        }
        if(cellOne==null || cellOne.isEmpty() && nowEnum!=null){
            excelEnums.add(nowEnum);
            nowEnum = null;
            isParseEnum = false;
            return;
        }
        if(cellOne.startsWith("@")){
            excelEnums.add(nowEnum);
            nowEnum = new ExcelEnum();
            if(rowData.size()>1){
                nowEnum.setDesc(rowData.get(1));
            }
            nowEnum.setName(cellOne.replace("@","").trim());
            return;
        }
        if (rowData.size()<3){
            ExportTask.nowTask.interrupt();//打断
            ExportTask.logger.error("枚举字段定义错误，枚举字段需要定义字段名、字段值、字段中文名!处理文件名："+analysisContext.readWorkbookHolder().getFile().getAbsolutePath()+" 处理的枚举名："+nowEnum.getName());
            return;
        }
        EnumFiled filed = new EnumFiled();
        filed.setFiledName(rowData.get(0));
        filed.setValue(rowData.get(1));
        filed.setFileName_CN(rowData.get(2));
        nowEnum.getFileds().add(filed);
    }




    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(nowEnum!=null){
            excelEnums.add(nowEnum);
            nowEnum = null;
            isParseEnum = false;
        }
        if(!ExportTask.canContinue()){
            return;
        }


        ProjectEnums projectEnums = ExcelTableManager.getProjectEnums(cfg.getName());
        for (ExcelEnum excelEnum : excelEnums) {
            projectEnums.getEnums().put(excelEnum.getName(),excelEnum);
        }
    }
}
